package com.wym.lottery.service;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;

public class NetService extends Service {
	private HttpClient httpClient;

	private NetBinder binder = new NetBinder();

	public class NetBinder extends Binder {

		public HttpClient getHttpClient() {
			return httpClient;
		}

		public boolean login(String username, String password) {
			boolean loginValidate = false;

			String host = "http://192.168.1.109:8080";
			String action = "/LotteryService/json/User";

			try {
				String queryUrl = host + action;

				HttpPost request = new HttpPost(queryUrl);
				List<NameValuePair> list = new ArrayList<NameValuePair>();
				list.add(new BasicNameValuePair("username", username));
				list.add(new BasicNameValuePair("password", password));
				request.setEntity(new UrlEncodedFormEntity(list, HTTP.UTF_8));

				HttpClient httpClient = binder.getHttpClient();
				HttpResponse response = httpClient.execute(request);
				String result = null;

				if (response.getStatusLine().getStatusCode() == 200) {

					String json = EntityUtils.toString(response.getEntity(), "utf-8");

					if (json != null) {
						JSONObject jsonObject = new JSONObject(json);
						result = jsonObject.get("statusCode").toString();
					}
					if ("200".equals(result))
						loginValidate = true;

				}
			} catch (UnsupportedEncodingException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (ClientProtocolException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (ParseException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			return loginValidate;

		}
	}

	@Override
	public IBinder onBind(Intent intent) {
		return binder;
	}

	@Override
	public void onCreate() {
		httpClient = new DefaultHttpClient();
		super.onCreate();
	}

}
